from java.awt import Color
from java.awt import Font
from java.lang import System
from java.lang import String
from java.lang import Double
from java.lang import Math
from java.util import Locale
from java.io import File


from jhplot.jadraw import JaKey
from jhplot.jadraw import JaText
from jhplot  import P1D
from jhplot  import HPlotJa

from hep.aida import *
#from fr.in2p3.ipnl.aidautilities import *

from jscinttools.scint.emissionspectrum import ModEmSpec
from jscinttools.utilities.aidautilities import *
from jscinttools.utilities.scintutilities import *
from jscinttools.utilities.jhplotutilities import *

Locale.setDefault(Locale.ENGLISH)

showFigures = True
writeFigures = not showFigures

""" Define colors and fonts"""
figType = [".png", ".eps"]
colors = [Color.BLUE, Color.RED, Color(0, 170, 0), Color.BLACK, Color.GRAY, Color.CYAN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.GREEN, Color.DARK_GRAY]
axisLabelFont = Font(Font.SERIF, Font.PLAIN, 25)
titleFont = Font(Font.SERIF, Font.PLAIN, 25)
legendFont = Font(Font.SERIF, Font.PLAIN, 25)
ticFont = Font(Font.SERIF, Font.PLAIN, 20)
statBoxFont = Font(Font.SERIF, Font.PLAIN, 15)

filePath = "/home/marc-antoine/Documents/ZnWO4/Emission_Spectra/"
fileName = ["301900mK.txt", "251600mK.txt", "201300mK.txt", "161100mK.txt", "120900mK.txt", "80700mK.txt", "49500mK.txt", "17600mK.txt", "8000mK.txt"]
fileNameX = ["XRays_300K.txt", "XRays_8K.txt"]


#outPath = filePath
outPath = filePath
outputFileRaw = "ZnWO4RawEmSpec"
outputFileCorr = "ZnWO4CorrEmSpec"
outputFileSmooth = "ZnWO4SmoothEmSpec"
outputFileCorrSpec = "ZnWO4CorrSpecEmSpec"
outputFileInteg = "ZnWO4IntegEmSpec"
outputFileX = "ZnWO4XEmSpec"

title = []
rawSpec = []
roundSpec = []
shortSpec = []
spec = []
corrSpec = []
smoothSpec = []
normAreaSpec = []
convSpec = []
key = []
temp = []
rawIntegVal = []
corrIntegVal = []
smoothIntegVal = []
convIntegVal = []
convIntegValNorm = []


spectrographT = P1D("SpectrographT", filePath + "SpectrographT.txt")
roundSpectrographT = ModEmSpec.roundEnergyVal(spectrographT)
shortSpectrographT = ModEmSpec.removeMultipleVal(roundSpectrographT)
rangedSpectrographT = []

pmQE = P1D("QE", filePath + File.separator + "R6095_QE.txt")

for i in range(len(fileName)):
	temp.append(Math.round(Double.valueOf(fileName[i].split("mK")[0])/1000.0))
	title.append(String.valueOf(temp[i]) + " K")
	rawSpec.append(P1D(title[i], filePath + fileName[i]))
	roundSpec.append(ModEmSpec.roundEnergyVal(rawSpec[i]))
	shortSpec.append(ModEmSpec.removeMultipleVal(roundSpec[i]))
	rangedSpectrographT.append(P1D("rangedSpectrographT", False, shortSpectrographT.range(0, shortSpec[i].getMin(0), shortSpec[i].getMax(0))))
	corrSpec.append(P1D(title[i], False, JHPlotUtil.divide(shortSpec[i], rangedSpectrographT[i])))
	smoothSpec.append(P1D(title[i], False,JHPlotUtil.smooth(corrSpec[i], 21)))
	normAreaSpec.append(ModEmSpec.normalizeAreaSpec(smoothSpec[i]))
	convSpec.append(ModEmSpec.convoluteQE(normAreaSpec[i], pmQE))
	
	key.append(JaKey(20,rawSpec[i].getTitle() , 0.675, i*0.05+0.30, "NDC"))
	
	rawIntegVal.append(ModEmSpec.integrateSpec(rawSpec[i]))
	corrIntegVal.append(ModEmSpec.integrateSpec(corrSpec[i]))
	smoothIntegVal.append(ModEmSpec.integrateSpec(smoothSpec[i]))
	convIntegVal.append(ModEmSpec.integrateSpec(convSpec[i]))



normSpecX300K = ModEmSpec.normalizeAmpSpec(JHPlotUtil.smooth(ModEmSpec.removeMultipleVal(ModEmSpec.roundEnergyVal(P1D("3.2 keV", filePath + fileNameX[0]))), 21))
normSpecX8K = ModEmSpec.normalizeAmpSpec(JHPlotUtil.smooth(ModEmSpec.removeMultipleVal(ModEmSpec.roundEnergyVal(P1D("3.2 keV", filePath + fileNameX[1]))), 21))
specX300K = P1D("3.2 keV - 300 K", False, normSpecX300K, color=colors[8], style="l", penWidth=2, symbolSize=0, errAll=False)
specX8K = P1D("3.2 keV - 8 K", False, normSpecX8K, color=colors[5], style="l", penWidth=2, symbolSize=0, errAll=False)

spec300K = P1D("30 eV - 302 K", False, ModEmSpec.normalizeAmpSpec(smoothSpec[0]), color=colors[1], style="l", penWidth=2, symbolSize=0, errAll=False)
spec8K = P1D("30 eV - 8 K", False, ModEmSpec.normalizeAmpSpec(smoothSpec[8]), color=colors[0], style="l", penWidth=2, symbolSize=0, errAll=False)

specX300KKey = JaKey(20, specX300K.getTitle() , 0.575, 0.25, "NDC", color=specX300K.getColor(), keyColor=specX300K.getColor(), font=ticFont)
specX8KKey = JaKey(20, specX8K.getTitle() , 0.575, 0.35, "NDC", color=specX8K.getColor(), keyColor=specX8K.getColor(), font=ticFont)
spec300KKey = JaKey(20, spec300K.getTitle() , 0.575, 0.20, "NDC", color=spec300K.getColor(), keyColor=spec300K.getColor(), font=ticFont)
spec8KKey = JaKey(20, spec8K.getTitle() , 0.575, 0.30, "NDC", color=spec8K.getColor(), keyColor=spec8K.getColor(), font=ticFont)
	
rawScalFac = rawIntegVal[0]
corrScalFac = corrIntegVal[0]
smoothScalFac = smoothIntegVal[0]
for i in range(len(fileName)):
	rawIntegVal[i] /= rawScalFac
	corrIntegVal[i] /= corrScalFac
	smoothIntegVal[i] /= smoothScalFac

rawInteg = P1D("Raw Integral", temp, rawIntegVal, style="p", color=colors[2], symbol=0, symbolSize=22)
corrInteg = P1D("Corrected Integral", temp, rawIntegVal, style="p", color=colors[1], symbol=1, symbolSize=16)
smoothInteg = P1D("Smoothed Integral", temp, rawIntegVal, style="p", color=colors[0], symbol=2, symbolSize=16)
rawIntegKey = JaKey(rawInteg.getSymbol(), rawInteg.getTitle() , 0.2, 0.65, "NDC", color=rawInteg.getColor(), keyColor=rawInteg.getColor(), font=legendFont)
corrIntegKey = JaKey(corrInteg.getSymbol(), corrInteg.getTitle() , 0.2, 0.70, "NDC", color=corrInteg.getColor(), keyColor=corrInteg.getColor(), font=legendFont)
smoothIntegKey = JaKey(smoothInteg.getSymbol(), smoothInteg.getTitle() , 0.2, 0.75, "NDC", color=smoothInteg.getColor(), keyColor=smoothInteg.getColor(), font=legendFont)


rawText = JaText("Raw Spectra", 0.15, 0.2, "NDC", color=colors[0], font=legendFont)
corrText = JaText("Corrected Spectra", 0.15, 0.2, "NDC", color=colors[0], font=legendFont)
smoothText = JaText("Corrected and Smoothed Spectra", 0.15, 0.2, "NDC", color=colors[0], font=legendFont)


"""
########################################################################
 Dump all the P1D in DPS in an Aida file 
########################################################################
"""
af = IAnalysisFactory.create()
tree = af.createTreeFactory().createTree(outPath + File.separator + "ZnWO4_EmissionSpectra" + ".aida", "xml", ITreeFactory.CREATE)
tree.mkdir("30eV_Hasylab")
#tree.mkdir("3200eV")
tuf = af.createTupleFactory(tree)
dpsf = af.createDataPointSetFactory(tree)

rawSpecDPS = []
corrSpecDPS = []
smoothSpecDPS = []
convSpecDPS = []
for i in range(len(fileName)):
	rawSpecDPS.append(dpsf.createCopy("/30eV_Hasylab/rawSpec" + String.valueOf(temp[i]) + "K", rawSpec[i].getIDataPointSet()))
	corrSpecDPS.append(dpsf.createCopy("/30eV_Hasylab/corrSpec" + String.valueOf(temp[i]) + "K", corrSpec[i].getIDataPointSet()))
	smoothSpecDPS.append(dpsf.createCopy("/30eV_Hasylab/smoothSpec" + String.valueOf(temp[i]) + "K", smoothSpec[i].getIDataPointSet()))
	convSpecDPS.append(dpsf.createCopy("/30eV_Hasylab/convSpec" + String.valueOf(temp[i]) + "K", convSpec[i].getIDataPointSet()))

spectrographDPS = dpsf.createCopy("/30eV_Hasylab/Spectrograph", spectrographT.getIDataPointSet())

corrFacTup = tuf.create("/30eV_Hasylab/corrFacTup", "corrFacTup", "double Temperature, double corrFac, double corrFacNorm")
corrFacDPS = dpsf.create("/30eV_Hasylab/corrFac", 2)
corrFacNormDPS = dpsf.create("/30eV_Hasylab/corrFacNorm", 2)
for i in range(len(fileName)):
	convIntegValNorm.append(convIntegVal[i]/convIntegVal[0])
	corrFacTup.fill(0, temp[i])
	corrFacTup.fill(1, convIntegVal[i])
	corrFacTup.fill(2, convIntegValNorm[i])
	corrFacTup.addRow()
	corrFacDPS.addPoint();
	corrFacDPS.point(i).coordinate(0).setValue(temp[i]);
	corrFacDPS.point(i).coordinate(1).setValue(convIntegVal[i]);
	corrFacNormDPS.addPoint();
	corrFacNormDPS.point(i).coordinate(0).setValue(temp[i]);
	corrFacNormDPS.point(i).coordinate(1).setValue(convIntegValNorm[i]);
qeDPS = dpsf.createCopy("R6095_QE", pmQE.getIDataPointSet())

#tree.commit()


########################################################################
# Graphical Attributs of Objects
########################################################################
for i in range(len(fileName)):
	rawSpec[i].setColor(colors[i])
	rawSpec[i].setStyle("l")
	rawSpec[i].setSymbolSize(0)
	rawSpec[i].setPenWidth(2)
	rawSpec[i].setErrAll(False)
	
	corrSpec[i].setColor(colors[i])
	corrSpec[i].setStyle("l")
	corrSpec[i].setSymbolSize(0)
	corrSpec[i].setPenWidth(2)
	corrSpec[i].setErrAll(False)
	
	smoothSpec[i].setColor(colors[i])
	smoothSpec[i].setStyle("l")
	smoothSpec[i].setSymbolSize(0)
	smoothSpec[i].setPenWidth(2)
	smoothSpec[i].setErrAll(False)
	
	key[i].setColor(rawSpec[i].color)
	key[i].setKeyColor(rawSpec[i].color)
	key[i].setPenWidth(2)
	key[i].setFont(legendFont)
	
spectrographT.setColor(colors[2])
spectrographT.setStyle("l")
spectrographT.setSymbolSize(0)
spectrographT.setPenWidth(2)
spectrographT.setErrAll(False)

pmQE.setColor(colors[2])
pmQE.setStyle("l")
pmQE.setSymbolSize(0)
pmQE.setPenWidth(2)
pmQE.setErrAll(False)

########################################################################
# Raw Spectra
########################################################################
""" Create the Plotter"""
rawPlotter = HPlotJa("Emission Spectra of ZnWO4", 600, 600, 1, 1, True)
rawPlotter.setGTitle("Emission Spectra of ZnWO_{4}", titleFont)
rawPlotter.antiAlias = False
rawPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
rawPlotter.setRange(300, 750, 0, 130)
rawPlotter.setLogScale(0, False)
rawPlotter.setLogScale(1, False)
rawPlotter.ticFont = ticFont
rawPlotter.showStatBox = False
rawPlotter.showKey(False)
rawPlotter.nameX = "Wavelength (nm)"
rawPlotter.nameY = "Intensity (a.u.)"

""" Plots all the JHep objects"""
for i in range(len(fileName)):
	rawPlotter.draw(rawSpec[i])
	rawPlotter.draw(key[i])
rawPlotter.draw(rawText)

""" Modifies the JaAxes and the axes labels"""
axes = rawPlotter.getPad()
axes.setLabelSpace(0, 0.0)
axes.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, axes)
HPlotJaUtil.setTickLabelZeroPositive(axes)

labX = rawPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, rawPlotter, 0.025)
labY = rawPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, rawPlotter, -0.00)
 
rawPlotter.update()

""" Saves or not the plot"""
if showFigures:
	rawPlotter.visible(True)
else:
	rawPlotter.visible(False)	
	for i in range(len(figType)):
		outFileName = outputFileRaw + figType[i]
		rawPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
rawPlotter.update()


########################################################################
# Corrected Spectra
########################################################################
""" Create the Plotter"""
corrPlotter = HPlotJa("Emission Spectra of ZnWO4", 600, 600, 1, 1, True)
corrPlotter.setGTitle("Emission Spectra of ZnWO_{4}", titleFont)
corrPlotter.antiAlias = False
corrPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
corrPlotter.setRange(300, 750, 0, 130)
corrPlotter.setLogScale(0, False)
corrPlotter.setLogScale(1, False)
corrPlotter.ticFont = ticFont
corrPlotter.showStatBox = False
corrPlotter.showKey(False)
corrPlotter.nameX = "Wavelength (nm)"
corrPlotter.nameY = "Intensity (a.u.)"

""" Plots all the JHep objects"""
for i in range(len(fileName)):
	corrPlotter.draw(corrSpec[i])
	corrPlotter.draw(key[i])
corrPlotter.draw(corrText)

""" Modifies the JaAxes and the axes labels"""
axes = corrPlotter.getPad()
axes.setLabelSpace(0, 0.0)
axes.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, axes)
HPlotJaUtil.setTickLabelZeroPositive(axes)

labX = corrPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, corrPlotter, 0.025)
labY = corrPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, corrPlotter, -0.00)
 
corrPlotter.update()

""" Saves or not the plot"""
if showFigures:
	corrPlotter.visible(True)
else:
	corrPlotter.visible(False)	
	for i in range(len(figType)):
		outFileName = outputFileCorr + figType[i]
		corrPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
corrPlotter.update()


########################################################################
# Smoothed Spectra
########################################################################
""" Create the Plotter"""
smoothPlotter = HPlotJa("Emission Spectra of ZnWO4", 600, 600, 1, 1, True)
smoothPlotter.setGTitle("Emission Spectra of ZnWO_{4}", titleFont)
smoothPlotter.antiAlias = False
smoothPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
smoothPlotter.setRange(300, 750, 0, 130)
smoothPlotter.setLogScale(0, False)
smoothPlotter.setLogScale(1, False)
smoothPlotter.ticFont = ticFont
smoothPlotter.showStatBox = False
smoothPlotter.showKey(False)
smoothPlotter.nameX = "Wavelength (nm)"
smoothPlotter.nameY = "Intensity (a.u.)"

""" Plots all the JHep objects"""
for i in range(len(fileName)):
	smoothPlotter.draw(smoothSpec[i])
	smoothPlotter.draw(key[i])
smoothPlotter.draw(smoothText)

""" Modifies the JaAxes and the axes labels"""
axes = smoothPlotter.getPad()
axes.setLabelSpace(0, 0.0)
axes.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, axes)
HPlotJaUtil.setTickLabelZeroPositive(axes)

labX = smoothPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, smoothPlotter, 0.025)
labY = smoothPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, smoothPlotter, -0.00)
 
smoothPlotter.update()

""" Saves or not the plot"""
if showFigures:
	smoothPlotter.visible(True)
else:
	smoothPlotter.visible(False)	
	for i in range(len(figType)):
		outFileName = outputFileSmooth + figType[i]
		smoothPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
smoothPlotter.update()


########################################################################
# Correction Spectrum
########################################################################
""" Create the Plotter"""
corrSpecPlotter = HPlotJa("Correction Spectrum", 600, 600, 1, 1, True)
corrSpecPlotter.setGTitle("Correction Spectrum", titleFont)
corrSpecPlotter.antiAlias = False
corrSpecPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
corrSpecPlotter.setRange(200, 1100, 0, 1.5)
corrSpecPlotter.setLogScale(0, False)
corrSpecPlotter.setLogScale(1, False)
corrSpecPlotter.ticFont = ticFont
corrSpecPlotter.showStatBox = False
corrSpecPlotter.showKey(False)
corrSpecPlotter.nameX = "Wavelength (nm)"
corrSpecPlotter.nameY = "Intensity (a.u.)"

""" Plots all the JHep objects"""
corrSpecPlotter.draw(spectrographT)

""" Modifies the JaAxes and the axes labels"""
axes = corrSpecPlotter.getPad()
axes.setLabelSpace(0, 0.0)
axes.setLabelSpace(1, 0.0)
#HPlotJaUtil.setTickLabelOneToPower(1, axes)
HPlotJaUtil.setTickLabelZeroPositive(axes)

labX = corrSpecPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, corrSpecPlotter, 0.025)
labY = corrSpecPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, corrSpecPlotter, -0.00)
 
corrSpecPlotter.update()

""" Saves or not the plot"""
if showFigures:
	corrSpecPlotter.visible(True)
else:
	corrSpecPlotter.visible(False)	
	for i in range(len(figType)):
		outFileName = outputFileCorrSpec + figType[i]
		corrSpecPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
corrSpecPlotter.update()

########################################################################
# Integrals
########################################################################
""" Create the Plotter"""
integPlotter = HPlotJa("Integrated LY of ZnWO_{4}", 600, 600, 1, 1, True)
integPlotter.setGTitle("Integrated LY of ZnWO_{4}", titleFont)
integPlotter.antiAlias = False
integPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
integPlotter.setRange(1, 1000, 0, 2)
integPlotter.setLogScale(0, True)
integPlotter.setLogScale(1, False)
integPlotter.ticFont = ticFont
integPlotter.showStatBox = False
integPlotter.showKey(False)
integPlotter.nameX = "Temperature (K)"
integPlotter.nameY = "Normalized LY (a.u.)"

""" Plots all the JHep objects"""
integPlotter.draw(rawInteg)
integPlotter.draw(corrInteg)
integPlotter.draw(smoothInteg)
integPlotter.draw(rawIntegKey)
integPlotter.draw(corrIntegKey)
integPlotter.draw(smoothIntegKey)


""" Modifies the JaAxes and the axes labels"""
axes = integPlotter.getPad()
axes.setLabelSpace(0, 0.0)
axes.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(0, axes)
HPlotJaUtil.setTickLabelZeroPositive(axes)

labX = integPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, integPlotter, 0.025)
labY = integPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, integPlotter, -0.00)
 
integPlotter.update()

""" Saves or not the plot"""
if showFigures:
	integPlotter.visible(True)
else:
	integPlotter.visible(False)	
	for i in range(len(figType)):
		outFileName = outputFileInteg + figType[i]
		integPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
integPlotter.update()


########################################################################
# Comparison Xrays - VUV
########################################################################
""" Create the Plotter"""
xPlotter = HPlotJa("Emission Spectra of ZnWO4 - X", 600, 600, 1, 1, True)
xPlotter.setGTitle("Emission Spectra of ZnWO_{4}", titleFont)
xPlotter.antiAlias = False
xPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
xPlotter.setRange(300, 750, 0, 1.1)
xPlotter.setLogScale(0, False)
xPlotter.setLogScale(1, False)
xPlotter.ticFont = ticFont
xPlotter.showStatBox = False
xPlotter.showKey(False)
xPlotter.nameX = "Wavelength (nm)"
xPlotter.nameY = "Intensity (a.u.)"

""" Plots all the JHep objects"""

xPlotter.draw(specX300K)
xPlotter.draw(specX8K)
xPlotter.draw(spec300K)
xPlotter.draw(spec8K)
xPlotter.draw(specX300KKey)
xPlotter.draw(specX8KKey)
xPlotter.draw(spec300KKey)
xPlotter.draw(spec8KKey)


""" Modifies the JaAxes and the axes labels"""
axes = xPlotter.getPad()
axes.setLabelSpace(0, 0.0)
axes.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, axes)
HPlotJaUtil.setTickLabelZeroPositive(axes)

labX = xPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, xPlotter, 0.025)
labY = xPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, xPlotter, -0.00)
 
xPlotter.update()

""" Saves or not the plot"""
if showFigures:
	xPlotter.visible(True)
else:
	xPlotter.visible(False)	
	for i in range(len(figType)):
		outFileName = outputFileX + figType[i]
		xPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
xPlotter.update()

print("That's all folks !")




